package cn.com.api.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.Avatar;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.qq.connect.utils.http.HttpClient;
import com.qq.connect.utils.http.PostParameter;
import com.qq.connect.utils.json.JSONException;
import com.qq.connect.utils.json.JSONObject;

import cn.com.api.entity.ApiT_member;
import cn.com.api.service.ApiT_memberService;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_API + "wechat/")
public class WechatController {

	private static Logger logger = Logger.getLogger(WechatController.class);

	@Autowired
	private ApiT_memberService apiT_memberService;

	/**
	 * 生成微信分享的config参数
	 * 
	 * @param address
	 *            要调用分享功能的页面的地址
	 */
	@RequestMapping("/shareconfigs")
	public void config(HttpServletRequest request, HttpServletResponse response, String address) throws IOException {
		// 分享后的回调地址
		String url = request.getParameter("address");// "http://www.eddaojia.com/webmvc/views/main/init"
		String jsapi_ticket = WeixinUtil.jsapi_ticket;

		Map<String, String> map = Sign.sign(jsapi_ticket, url);
		map.put("appid", WeixinUtil.appId);
		// sign = SignUtil.createLinkString(map, null);
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 获取微信用户的信息
	 * 
	 */
	@RequestMapping("/getWechatUserInfo")
	public void getWechatUserInfo(HttpServletRequest request, HttpServletResponse response, String code)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> wx = WeixinUtil.getOpenId(WeixinUtil.appId, WeixinUtil.secret, code);
		if (wx != null) {
			String openid = wx.get("openid");
			String access_token = wx.get("access_token");
			System.out.println("================openid:" + openid);
			if (openid != null) {
				// 获取微信用户信息
				ApiT_member t_member = new ApiT_member();
				Map<String, String> wechat_userinfo = WeixinUtil.getUserInfo2(openid, access_token);
				t_member.setOpenid(openid);
				t_member.setC_nick(wechat_userinfo.get("nickname"));
				t_member.setC_avatar(wechat_userinfo.get("headimgurl"));
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成");
				map.put(Utils.DATAS, t_member);
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
				map.put(Utils.MESSAGE, "没有获取到用户信息！");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "效验失败！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));

	}

	/**
	 * @Description: 获取QQ用户信息
	 * @param request
	 * @param response
	 * @param code
	 *            回去QQ用户信息的凭证
	 * @return void
	 * @throws @author
	 *             yewl
	 * @date 2017年3月1日
	 */
	@RequestMapping("/getQQUserInfo")
	public void getQQUserInfo(HttpServletRequest request, HttpServletResponse response, String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		String accessToken = null, openID = null;
		try {
			HttpClient client = new HttpClient();
			AccessToken accessTokenObj = new AccessToken(client.post(QQUtil.accessTokenURL,
					new PostParameter[] { new PostParameter("client_id", QQUtil.app_ID),
							new PostParameter("client_secret", QQUtil.app_KEY),
							new PostParameter("grant_type", "authorization_code"), new PostParameter("code", code),
							new PostParameter("redirect_uri", QQUtil.redirect_URI) },
					Boolean.valueOf(false)));
			accessToken = accessTokenObj.getAccessToken();
			OpenID openIDObj = new OpenID(accessToken);
			openID = openIDObj.getUserOpenID();
			JSONObject asJSONObject = client.get(QQUtil.getUserInfoURL,
					new PostParameter[] { new PostParameter("openid", openID),
							new PostParameter("oauth_consumer_key", QQUtil.app_ID),
							new PostParameter("access_token", accessToken), new PostParameter("format", "json") })
					.asJSONObject();
			if (asJSONObject != null) {
				try {
					int ret = asJSONObject.getInt("ret");
					if (0 != ret) {
						String msg = asJSONObject.getString("msg");
					} else {
						ApiT_member apiT_member = new ApiT_member();
						apiT_member.setOpenid(openID);
						apiT_member.setC_nick(asJSONObject.getString("nickname"));
						apiT_member.setC_avatar(asJSONObject.getString("figureurl_qq_2"));
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "操作完成");
						map.put(Utils.DATAS, apiT_member);
					}
				} catch (JSONException jsone) {
					map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
					map.put(Utils.MESSAGE, "没有获取到用户信息！");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
			map.put(Utils.MESSAGE, "没有获取到用户信息！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

}
